package com.xinsoft.controller.device;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.*;
import com.xinsoft.entity.po.CusDeviceBreakdown;
import com.xinsoft.entity.po.CusRepaire;
import com.xinsoft.entity.po.SysAction;
import com.xinsoft.entity.po.SysUser;
import com.xinsoft.entity.vo.CusRepaireVo;
import com.xinsoft.entity.vo.SysClientVo;
import com.xinsoft.entity.vo.SysNoticeUserVo;
import com.xinsoft.service.*;
import com.xinsoft.service.impl.CusDeviceBreakdownServiceImpl;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cus/deviceRepair")
public class CusDeviceRepaireController {

    @Autowired
    private CusRepaireService cusRepaireService;

    @Autowired
    private CusDeviceBreakdownService cusDeviceBreakdownService;


    @Autowired
    private SysDocumentNumService sysDocumentNumService;

    @Resource
    private SysNoticeSetService sysNoticeSetService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysNoticeService sysNoticeService;

    @Autowired
    private SysActionService actionService;

    /**
     * 新增故障维修记录
     */

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/add")
    public Response<?> add(@RequestBody CusBreakDownRepaireDTO cusBreakDownRepaireDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(cusBreakDownRepaireDTO.getCusRepaireDTO());
        ValidatorUtils.validateEntity(cusBreakDownRepaireDTO.getCusDeviceBreakdownDTO());
        if(StrUtil.isNotEmpty(cusBreakDownRepaireDTO.getCusDeviceBreakdownDTO().getBreakdownCode())){
            sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.DEVICE_BREAKDOWN_DOCUMENT);
        }
        return Response.succeed(cusRepaireService.addCusBreakDownRepaireRecord(cusBreakDownRepaireDTO));
    }

    /**
     * 更新故障维修记录
     */

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/edit")
    public Response<?> edit(@RequestBody CusBreakDownRepaireDTO cusBreakDownRepaireDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(cusBreakDownRepaireDTO.getCusRepaireDTO());
        ValidatorUtils.validateEntity(cusBreakDownRepaireDTO.getCusDeviceBreakdownDTO());
        return Response.succeed(cusRepaireService.editCusBreakDownRepaireRecord(cusBreakDownRepaireDTO));
    }

    /**
     * 提交维修记录
     */

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/submit")
    public Response<?> submit(@RequestBody CusBreakDownRepaireDTO cusBreakDownRepaireDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(cusBreakDownRepaireDTO);
        //先更新未提交状态，最后更新为待验收
        cusBreakDownRepaireDTO.getCusDeviceBreakdownDTO().setRepaireStatus(Const.RepairStatus.SUBMIT);
        cusBreakDownRepaireDTO.getCusRepaireDTO().setRepaireStatus(Const.RepairRecordStatus.COMPLETED);
        if(cusBreakDownRepaireDTO.getCusDeviceBreakdownDTO().getId()==null){
            //保存
            sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.DEVICE_BREAKDOWN_DOCUMENT);
            CusRepaire cusRepaire = cusRepaireService.addCusBreakDownRepaireRecord(cusBreakDownRepaireDTO);
            this.sendContent(cusRepaire.getId());
        }else{
            CusRepaire cusRepaire = cusRepaireService.editCusBreakDownRepaireRecord(cusBreakDownRepaireDTO);
            this.sendContent(cusRepaire.getId());
        }
        //更新故障报修
        CusDeviceBreakdown cusDeviceBreakdown = new CusDeviceBreakdown();
        cusDeviceBreakdown.setId(cusBreakDownRepaireDTO.getCusDeviceBreakdownDTO().getId());
        cusDeviceBreakdown.setRepaireStatus(Const.RepairStatus.PROCESSED_ACCEPTANCE);
        cusDeviceBreakdownService.updateById(cusDeviceBreakdown);
        return Response.succeed();
    }

    /**
     * 获取维修记录详情
     */
    @GetMapping("/detail")
    public Response<?> detail(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        return Response.succeed(cusRepaireService.getCusBreakDownRepaire(id));
    }

    /**
     * 删除维修记录
     */

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Integer> ids) {
        cusRepaireService.del(ids);
        return Response.succeed();
    }

    /**
     * 维修记录分页
     */
    @PostMapping("/pageList")
    public Response<?> pageList(@RequestBody CusRepairePageParam cusDeviceRepairePageParam) {
        return Response.succeed(cusRepaireService.findPageListByParam(cusDeviceRepairePageParam));
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    public Response<?> export(@RequestBody CusRepairePageParam cusDeviceRepairePageParam, HttpServletResponse response) throws Exception {
        List<CusRepaireVo> cusRepaireVoList = cusRepaireService.findListByParam(cusDeviceRepairePageParam);
        ExcelUtils.exportByEasypoi(cusRepaireVoList, CusRepaireVo.class, "维修记录", "维修记录", response, "维修记录");
        return Response.succeed();
    }

    /**
     * 发送消息
     */
    public void sendContent(Integer id) {
        List<SysNoticeSetDTO> sysNoticeSetDTOList = sysNoticeSetService.getSysNoticeSetByActionId(Const.ACTION.MAINTENANCE_RECORDS);
        SysNoticeSetDTO noticeSetDTO = sysNoticeSetDTOList.get(0);
        List<SysNoticeUserVo> sysNoticeUserList = noticeSetDTO.getSysNoticeUserList();
        if (ObjectUtil.isEmpty(sysNoticeUserList)) return ;

        List<Integer> receiveIds = new ArrayList<>();
        List<Integer> deptIds = new ArrayList<>();
        sysNoticeUserList.forEach(item ->{
            if (Objects.equals(item.getDepOrUser(), Const.NOTICE_DEPT)) {
                deptIds.add(item.getDepId());
            }
            if (Objects.equals(item.getDepOrUser(), Const.NOTICE_USER)) {
                receiveIds.add(item.getUserId());
            }
        });
        // 设置接收人
        if (CollectionUtil.isNotEmpty(deptIds)) {
            List<SysUser> userList = sysUserService.list(Wrappers.lambdaQuery(SysUser.class)
                    .eq(SysUser::getStatus, Const.USER_STATUS_NORMAL)
                    .in(SysUser::getDeptId, deptIds));
            if (CollectionUtil.isNotEmpty(userList)) {
                List<Integer> userIdsOfDept = userList.stream().map(SysUser::getId).collect(Collectors.toList());
                receiveIds.addAll(userIdsOfDept);
            }
        }
        if (ObjectUtil.isEmpty(receiveIds)) return ;
        SysNoticeDTO noticeDTO = new SysNoticeDTO();
        SysAction sysAction = actionService.getById(Const.ACTION.MAINTENANCE_RECORDS);
        noticeDTO.setFromUserId(1);   // 管理员发送
        noticeDTO.setContent(noticeSetDTO.getNoticeContext());
        noticeDTO.setReceiveIds(receiveIds);
        noticeDTO.setTitle(sysAction.getActionName());
        noticeDTO.setContentUrlParam(noticeSetDTO.getHrefUrl() + id);
        sysNoticeService.send(noticeDTO);
        return ;
    }
}
